package socket;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

public class SocketOutput {

	private OutputStream output;

	public SocketOutput(OutputStream output) {
		super();
		this.output = output;
	}

	void writeInt(int value) throws IOException {
		ByteBuffer byteBuffer = ByteBuffer.allocate(4);
		byteBuffer.putInt(value);
		output.write(byteBuffer.array());
	}

	public void writeString(int kind, String str) throws IOException {
		write(kind, str.getBytes());
	}

	public void write(int kind, byte[] buffer) throws IOException {
		write(kind, new ByteArrayInputStream(buffer));
	}

	public void write(int kind, InputStream in) throws IOException {
		writeInt(kind);
		byte[] buffer = ByteUtils.inputStreamToByte(in);
		writeInt(buffer.length);
		output.write(buffer);
	}

}
